<template> 
  <div class="bronze-restoration">
    <div class="header-container">
      <button @click="goBack" class="back-button" aria-label="返回">
        <i class="fas fa-arrow-left"></i> 返回
      </button>
      <div class="header">
        <h1>知识问答</h1>
      </div>
    </div>

    <div id="RecogChallenge">
      <div class="container">
        <h1>青铜知识问答</h1>

        <div v-if="loading" class="loading-spinner">
          <div class="spinner"></div>
        </div>

        <div v-if="error" class="error-message">
          {{ error }}
        </div>

        <div v-if="!loading && !error && currentQuestion" class="question-box">
          <div class="question-header">
            <span class="question-number">第 {{ currentQuestionIndex + 1 }}/10 题</span>
            <span class="score">累计分数: <strong>{{ score }}</strong></span>
          </div>
          <h2>{{ currentQuestion.question }}</h2>
          <div class="options">
            <button 
              v-for="option in ['A', 'B', 'C', 'D']" 
              :key="option"
              @click="selectOption(option)"
              :class="['option-button', { selected: selectedOption === option }]"
            >
              {{ currentQuestion['option' + option] }}
            </button>
          </div>
          <div class="action-buttons">
            <button 
              @click="submitAnswer" 
              :disabled="!selectedOption || result"
              class="submit-btn"
            >
              提交
            </button>
            <button 
              @click="collectQuestion" 
              class="collect-btn"
            >
              收藏
            </button>
          </div>
        </div>

        <div v-if="result" class="result-box">
          <p :class="{ 'correct': result.correct, 'incorrect': !result.correct }">
            {{ result.correct ? '回答正确!' : '回答错误.' }}
          </p>
          <p v-if="!result.correct">正确答案是: {{ result.correctAnswer }}</p>
          <button @click="nextQuestion" class="next-btn">
            {{ currentQuestionIndex + 1 < questions.length ? '下一题' : '完成' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 模态框 -->
    <div v-if="showModal" class="modal-overlay">
      <div class="modal-content">
        <h2>{{ modalTitle }}</h2>
        <p>{{ modalMessage }}</p>
        <button @click="closeModal" class="close-modal-btn">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { BASE_URL } from '@/config.js';
export default {
  name: 'BronzeRestoration',
  data() {
    return {
      questions: [], // 存储10道题目
      currentQuestionIndex: 0, // 当前题目索引
      currentQuestion: null, // 当前题目对象
      selectedOption: null, // 用户选择的选项
      result: null, // 当前题目的结果
      loading: true, // 加载状态
      error: null, // 错误信息
      score: 0, // 累计分数
      showModal: false, // 是否显示模态框
      modalTitle: '', // 模态框标题
      modalMessage: '', // 模态框内容
      userId: null,
      fromSection: null,
    };
  },
  mounted() {
    this.userId = localStorage.getItem('userId');
    console.log('Stored userId on mount:', this.userId);
    this.fetchQuestions();
    this.fromSection = this.$route.query.fromSection;
  },
  computed: {
    computedUserId() {
      const id = localStorage.getItem('userId');
      console.log('Computed userId (raw):', id);
      return id ? parseInt(id, 10) : null;
    }
  },
  methods: {
    goBack() {
      if (this.fromSection !== null) {
        this.$router.push({ name: 'Home', query: { scrollToSection: this.fromSection } });
      } else {
        this.$router.push({ name: 'Home' });
      }
    },
    async fetchQuestions() {
      this.loading = true;
      this.error = null;
      try {
        // 优先尝试使用新的API一次性获取10道题
        const response = await axios.get(`${BASE_URL}/api/questions`, {
          params: { count: 10 }
        });
        this.questions = response.data;
        this.currentQuestion = this.questions[this.currentQuestionIndex];
      } catch (error) {
        console.error('Error fetching questions:', error);
        this.error = '获取题目失败，请刷新页面重试。';
      } finally {
        this.loading = false;
      }
    },
    // 如果后端无法修改，使用此方法进行10次API调用

    async fetchQuestions() {
      this.loading = true;
      this.error = null;
      const fetchPromises = [];
      for (let i = 0; i < 10; i++) {
        fetchPromises.push(axios.get(`${BASE_URL}/api/question`));
      }
      try {
        const responses = await Promise.all(fetchPromises);
        this.questions = responses.map(res => res.data);
        this.currentQuestion = this.questions[this.currentQuestionIndex];
      } catch (error) {
        console.error('Error fetching questions:', error);
        this.error = '获取题目失败，请刷新页面重试。';
      } finally {
        this.loading = false;
      }
    },

    selectOption(option) {
      this.selectedOption = option;
    },
    async submitAnswer() {
      if (!this.selectedOption || !this.currentQuestion) return;

      try {
        const response = await axios.post(`${BASE_URL}/api/answer`, {
          questionId: this.currentQuestion.question_id,
          answer: this.selectedOption
        });
        this.result = response.data;
        if (this.result.correct) {
          this.score += 10; // 每题10分
        }
      } catch (error) {
        console.error('Error submitting answer:', error);
        this.error = '提交答案失败，请重试。';
      }
    },
    nextQuestion() {
      this.result = null;
      this.selectedOption = null;
      if (this.currentQuestionIndex + 1 < this.questions.length) {
        this.currentQuestionIndex += 1;
        this.currentQuestion = this.questions[this.currentQuestionIndex];
      } else {
        this.calculateEvaluation();
      }
    },
    calculateEvaluation() {
      let message = '';
      let title = '';
      if (this.score < 60) {
        title = '不及格';
        message = '再接再厉，继续阅读青铜学习的知识吧！';
      } else if (this.score < 70) {
        title = '及格';
        message = '不错，但还有进步空间，继续加油！';
      } else if (this.score < 80) {
        title = '良好';
        message = '表现良好，继续保持！';
      } else if (this.score < 90) {
        title = '优秀';
        message = '非常棒！你对青铜知识掌握得很好！';
      } else if (this.score < 100) {
        title = '卓越';
        message = '几乎完美！继续深入学习青铜知识吧！';
      } else {
        title = '满分';
        message = '完美无缺！你是青铜知识的达人！';
      }
      this.modalTitle = title;
      this.modalMessage = message;
      this.showModal = true;
    },
    closeModal() {
      this.showModal = false;
      // 可选择重置或跳转其他页面
      this.$router.push('/'); // 例如，跳转回主页
    },
    async collectQuestion() {
      const userId = localStorage.getItem('userId');
      this.userId = userId;
      console.log('userId:', this.userId);
      if(!this.userId) {
        alert("userId未正确传递");
        return;
      }
      console.log('collectQuestion method called');
      console.log('localStorage userId:', localStorage.getItem('userId'));
      console.log('component storedUserId:', this.userId);
      console.log('computed userId:', this.computedUserId);

      if (!this.currentQuestion) {
        console.log('currentQuestion:', this.currentQuestion);
        alert('无法收藏题目：当前题目不存在');
        return;
      }

      try {
        const response = await axios.post(`${BASE_URL}/api/collect`, {
          userId: this.userId,
          questionId: this.currentQuestion.question_id
        });
        
        console.log('Collection response:', response.data);
        
        if (response.data.message) {
          alert('题目已收藏！');
        } else {
          alert('收藏失败，请重试。');
        }
      } catch (error) {
        console.error('Error collecting question:', error);
        alert('收藏失败，请稍后再试。');
      }
    },
  }
};
</script>

<style scoped>
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.bronze-restoration {
background-image: url('@/assets/m18.jpg'); 
background-repeat: no-repeat; /* 背景图不重复 */
background-size: cover; /* 背景图覆盖整个区域 */
background-position: center; /* 背景图居中 */
background-attachment: fixed; /* 背景图固定 */
  min-height: 100vh;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #f5e4c3;
}

.header-container {
  background-color: rgba(94, 75, 60, 0.9);
  border-radius: 15px;
  padding: 5px 30px;
  margin-bottom: 40px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
  display: flex;              /* 保持为 flex 容器 */
  justify-content: center;    /* 水平居中对齐子元素 */
  align-items: center;        /* 垂直居中对齐子元素 */
  position: relative;         /* 允许绝对定位子元素 */
  margin-top: 52px;
  margin-left: 230px;
  margin-right: 230px;
}

.header {
  display: flex;
  align-items: center; /* 保持垂直居中对齐 */
  /* 保持水平布局 */
}

.back-button {
  position: absolute;        /* 绝对定位 */
  left: 20px;                /* 左侧距离 */
  background-color: #5e4b3c;
  color: #f5e4c3;
  border: none;
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  margin-right: 0;           /* 移除右边距 */
  /* 移除 margin-bottom: 10px; */
  transition: background-color 0.3s, transform 0.3s;
  box-shadow: 0 4px 10px rgba(94, 75, 60, 0.5);
}

.back-button:hover {
  background-color: #8b6e4c;
  transform: translateY(-2px);
}

.header h1 {
  font-size: 28px;
  color: #d4af37;
  font-family: 'Orbitron', sans-serif;
  text-align: center; /* 确保标题居中 */
  flex: 1;            /* 让标题占据剩余空间 */
}

#RecogChallenge {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  background-color: rgba(45, 45, 45, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.7);
  max-width: 700px;
  width: 100%;
}

.container h1 {
  color: #d4af37;
  margin-bottom: 30px;
  font-family: 'Orbitron', sans-serif;
  text-align: center;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

.spinner {
  border: 6px solid rgba(212, 175, 55, 0.3);
  border-top: 6px solid #d4af37;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  background-color: rgba(255, 69, 0, 0.8);
  color: #ffffff;
  padding: 15px 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  text-align: center;
}

.question-box {
  background-color: rgba(94, 75, 60, 0.85);
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

.question-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.question-number {
  font-size: 18px;
}

.score {
  font-size: 18px;
}

.score strong {
  font-size: 24px;
  color: #d4af37;
}

.question-box h2 {
  color: #f5e4c3;
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
}

.options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 25px;
}

.option-button {
  background-color: #5e4b3c;
  color: #f5e4c3;
  border: none;
  padding: 12px 20px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s, transform 0.3s;
  box-shadow: 0 4px 10px rgba(94, 75, 60, 0.5);
}

.option-button:hover {
  background-color: #8b6e4c;
  transform: translateY(-2px);
}

.option-button.selected {
  background-color: #d4af37;
  color: #2c2c2c;
}

.action-buttons {
  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 20px; /* 按钮之间的间距 */
  align-items: center;
  margin-top: 20px; /* 可选: 添加顶部间距 */
}

.submit-btn {
  background-color: #4caf50; /* 深绿色 */
  color: #ffffff;
  border: none;
  padding: 12px 25px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s, transform 0.3s;
  box-shadow: 0 4px 10px rgba(76, 175, 80, 0.5);
  /* 修改 margin-left 为自动对齐 */
}

.submit-btn:hover {
  background-color: #45a049;
  transform: translateY(-2px);
}

.submit-btn:disabled {
  background-color: rgba(76, 175, 80, 0.5);
  cursor: not-allowed;
}

.collect-btn {
  background-color: #d4af37; /* 金色 */
  color: #2c2c2c;
  border: none;
  padding: 12px 25px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s, transform 0.3s;
  box-shadow: 0 4px 10px rgba(212, 175, 55, 0.5);
  /* 修改 margin-right 为自动对齐 */
}

.collect-btn:hover {
  background-color: #f5e4c3;
  color: #2c2c2c;
  transform: translateY(-2px);
}

.result-box {
  background-color: rgba(94, 75, 60, 0.9);
  border-radius: 15px;
  padding: 25px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
  text-align: center;
}

.result-box p {
  font-size: 20px;
  margin-bottom: 15px;
}

.result-box p.correct {
  color: #4caf50; /* 绿色 */
  font-weight: bold;
}

.result-box p.incorrect {
  color: #f44336; /* 红色 */
  font-weight: bold;
}

.next-btn {
  background-color: #d4af37; /* 金色 */
  color: #2c2c2c;
  border: none;
  padding: 12px 25px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s, transform 0.3s;
  box-shadow: 0 4px 10px rgba(212, 175, 55, 0.5);
}

.next-btn:hover {
  background-color: #f5e4c3;
  transform: translateY(-2px);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(28, 40, 39, 0.8); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #2c2c2c;
  padding: 30px;
  border-radius: 15px;
  text-align: center;
  color: #f5e4c3;
  max-width: 500px;
  width: 80%;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.7);
}

.modal-content h2 {
  font-size: 28px;
  margin-bottom: 20px;
}

.modal-content p {
  font-size: 18px;
  margin-bottom: 30px;
}

.close-modal-btn {
  background-color: #d4af37;
  color: #2c2c2c;
  border: none;
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s, transform 0.3s;
}

.close-modal-btn:hover {
  background-color: #f5e4c3;
  transform: translateY(-2px);
}
</style>
